import random

from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code


# Create your views here.

class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')
        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'message': '发送短信过于频繁'}, status=429)
        # 创建redis管道
        pl = redis_conn.pipeline()
        # 保存短信验证码
        pl.setex('sms_%s' % mobile, 60 * 5, sms_code)
        # 写入send_flag
        pl.setex('send_flag_%s' % mobile, 60, 1)
        # 执行请求
        pl.execute()
        # 发送短信验证码
        # success_flag = send_sms_code.delay(mobile, sms_code)
        # if success_flag == -1:
        #     return http.JsonResponse({'message': '发送失败'}, status=400)
        print(sms_code)
        return http.JsonResponse({'message': 'OK'})
